package com.pgytesting.secondhandcar.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.pgytesting.secondhandcar.model.AdministratorInformation;
import com.pgytesting.secondhandcar.service.AdministratorInformationService;
import com.pgytesting.secondhandcar.vo.ResponseMessage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminLoginController {

	@Autowired
	private AdministratorInformationService administratorInformationService;
	
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	public ResponseMessage login(@RequestBody @Valid AdministratorInformation administratorInformation, BindingResult bindingResult,HttpServletResponse response) {
		try {
			if (bindingResult.hasErrors()) {
				List<FieldError> ls = bindingResult.getFieldErrors();
				Map<String,String> map = new HashMap<String,String>();
	            for (int i = 0; i < ls.size(); i++) {
	            	map.put(ls.get(i).getField(), ls.get(i).getDefaultMessage());
	            }
	            return ResponseMessage.errorResponse(map);
	        }
			return administratorInformationService.verificationLogin(administratorInformation);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.errorResponse("管理员登录出现异常");
		}
	}
	
	@RequestMapping(value = "/logout")
	public ResponseMessage logout(HttpSession httpSession) {
		try {
			httpSession.removeAttribute("user");
			return ResponseMessage.successResponse("管理员退出登录成功");
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.errorResponse("管理员退出登录出现异常");
		}
	}
}
